package com.cby.springboot.demo.service;

import com.cby.springboot.demo.bean.AdminMenu;
import com.cby.springboot.demo.bean.AdminRoleMenu;
import com.cby.springboot.demo.mapper.AdminMenuMapper;
import com.cby.springboot.demo.mapper.AdminRoleMenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Service("adminMenuService")
public class AdminMenuServiceImpl implements AdminMenuService{

    @Autowired
    AdminMenuMapper adminMenuMapper;

    @Autowired
    AdminRoleMenuMapper adminRoleMenuMapper;

    @Override
    public AdminMenu findById(int id) {
        return adminMenuMapper.findById(id);
    }

    @Override
    public List<AdminMenu> findAllByParentId(int parentId) {
        return adminMenuMapper.findAllByParentId(parentId);
    }


    @Override
    public List<AdminMenu> getMenusByRoleId(int rid) {
        List<Integer> menuIds = adminRoleMenuMapper.findAllByRid(rid)
                .stream().map(AdminRoleMenu::getMid).collect(Collectors.toList());
        List<AdminMenu> menus = findAllMenuByIds(menuIds);

        handleMenus(menus);
        return menus;
    }

    private List<AdminMenu> findAllMenuByIds(List<Integer> menuIds) {
        int size = menuIds == null ? 0 : menuIds.size();
        List<AdminMenu> result = new ArrayList<>();
        if(size > 0) {
            for (int i = 0; i < size; i++) {
                result.add(findById(menuIds.get(i)));
            }
        }
        return result;
    }

    public void handleMenus(List<AdminMenu> menus) {
        for (AdminMenu menu : menus) {
            List<AdminMenu> children = findAllByParentId(menu.getId());
            menu.setChildren(children);
        }

        menus.removeIf(menu -> menu.getParentId() != 0);
    }
}
